package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;


/**
 * Aspect:标识此类为切面类
 */
@Aspect
@Component
public class LogAspect {
    /**
     * @Before注解: 前置通知, 在执行目标方法之前执行
     */
    @Before(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")

    public void before(JoinPoint joinPoint) {
        /*
            1.获取目标方法名
            2.获取目标方法参数
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());

        System.out.println("[前置通知]:" + name + "方法开始执行,参数为:" + args);
    }

    /**
     * @After: 后置通知, 在执行目标方法之后执行
     */
    @After(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void after(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[后置通知]:" + name + "方法执行结束");
    }

    /**
     * @Afterreturn: 返回通知, 在执行目标方法之后执行, 并且可以获取目标方法的返回值
     */
    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[返回通知]:" + name + "方法正常结束,返回值为:" + result);
    }

    /**
     * @AfterThrowing: 异常通知, 在执行目标方法之后执行, 并且可以获取目标方法的异常
     */
    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {
        String name = joinPoint.getSignature().getName();
        System.out.println("[异常通知]:" + name + "方法抛出异常,异常信息为:" + ex.getMessage());
    }

    /**
     * @Around: 环绕通知, 环绕目标方法执行;
     * 等价于: 前置通知 + 返回通知 + 异常通知 + 后置通知
     */
    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            // 1.前置通知
            System.out.println("环绕通知:前置通知");
            // 2.执行目标方法
            result = joinPoint.proceed();

            // 3.返回通知
            System.out.println("环绕通知:返回通知");
        } catch (Throwable e) {
            // 4.异常通知
            System.out.println("环绕通知:异常通知");
            throw new RuntimeException(e);
        } finally {
            System.out.println("环绕通知:后置通知");
            // 5.后置通知
        }
        return result;

    }
}
